package cn.edu.bs.web.controller;

import cn.edu.bs.domain.UserExample;
import cn.edu.bs.service.UserService;
import cn.edu.bs.web.request.user.UserFormCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author bs
 */
@Controller
public class AuthController extends BaseController {

    private final String ADMIN_USERNAME = "admin";
    private final String ADMIN_PASSWORD = "123456";

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String toLoginPage(Model model) {
        return "admin/login";
    }

    @PostMapping("/login")
    public String doLogin(
            UserFormCommand command,
            Model model,
            HttpServletRequest request,
            HttpServletResponse response,
            HttpSession session
    ) throws ServletException, IOException {
        if (!checkAccount(command)) {
            model.addAttribute("error", "用户名或密码错误");
            return "admin/login";
        } else {
            session.setAttribute("username", command.getUsername());
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String doLogout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }

    private Boolean checkAccount(UserFormCommand command) {
        Boolean flag = false;
        flag = ADMIN_USERNAME.equals(command.getUsername()) && ADMIN_PASSWORD.equals(command.getPassword());
        if (flag) {
            return true;
        }
        UserExample example = new UserExample();
        example.createCriteria()
                .andUsernameEqualTo(command.getUsername())
                .andPasswordEqualTo(command.getPassword());
        if (userService.countByExample(example) == 1) {
            flag = true;
        }
        return flag;
    }

}
